package aliyun

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"strings"
)

type Service struct {
	client   *dysmsapi.Client
	signName string
}

func NewService(c *dysmsapi.Client, signName string) *Service {
	return &Service{
		client:   c,
		signName: signName,
	}
}

func (s Service) Send(ctx context.Context, tpl string, args []string, numbers ...string) error {
	request := dysmsapi.CreateSendSmsRequest()
	request.Scheme = "https"

	request.PhoneNumbers = strings.Join(numbers, ",")
	request.SignName = s.signName
	request.TemplateCode = tpl

	argsMap := make(map[string]string, len(args))
	for _, arg := range args {
		argsMap["code"] = arg
	}
	bCode, err := json.Marshal(argsMap)
	if err != nil {
		return err
	}
	request.TemplateParam = string(bCode)
	resp, err := s.client.SendSms(request)
	if err != nil {
		return err
	}

	if resp.Code != "OK" {
		return fmt.Errorf("发送短信失败: %s :%s", resp.Message, resp.Code)
	}

	return nil
}
